package com.qdlc.p2p.dal.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.RedEnvelopeAttachedDao;
import com.qdlc.p2p.dal.dto.RedEnvelope;
import com.qdlc.p2p.dal.dto.RedEnvelopeAttached;
import com.qdlc.p2p.dal.model.RedEnvelopeAttachedModel;

/**
 * 红包附属DAO接口
 * @author ylx
 * @version 2.0
 * @since 2015年04月22日 13时53分05秒
 */
@Repository(value = "redEnvelopeAttachedDao")
public class RedEnvelopeAttachedDaoImpl extends BaseDaoImpl<RedEnvelopeAttached> implements RedEnvelopeAttachedDao {

    @SuppressWarnings("unchecked")
    @Override
    public RedEnvelopeAttached getRedEnvelopeAttachedById(long id) {
        String jpql = "from RedEnvelopeAttached where id = ?1";
        Query query = em.createQuery(jpql);
        query.setParameter(1, id);
        List<RedEnvelopeAttached> list = query.getResultList();
        if (list != null && list.size() >= 0) {
            return (RedEnvelopeAttached) list.get(0);
        } else {
            return null;
        }
    }

	@Override
	public List<RedEnvelopeAttached> list(long redEnvelopeId) {
		QueryParam param = QueryParam.getInstance();
		param.addParam("redEnvelope.id", redEnvelopeId).addParam("isDelete", RedEnvelopeAttachedModel.IS_NO_DELETE);
		return this.findByCriteria(param);
	}

	@Override
	public void deleteByRedEnvelopeId(long redEnvelopeId) {
		String jpql = "update RedEnvelopeAttached set isDelete = ?1 where redEnvelope.id = ?2";
		Query query = em.createQuery(jpql);
		query.setParameter(1, RedEnvelopeAttachedModel.IS_DELETE);
		query.setParameter(2, redEnvelopeId);
		query.executeUpdate();
	}

	@Override
	public void save(List<RedEnvelopeAttached> list) {
		if (list != null && list.size() > 0) {
			for (RedEnvelopeAttached attached : list) {
				this.save(attached);
			}
		}
	}

	@Override
	public void save(List<RedEnvelopeAttached> list, RedEnvelope redEnvelope) {
		if (list != null && list.size() > 0) {
			for (RedEnvelopeAttached attached : list) {
				attached.setRedEnvelope(redEnvelope);
				this.save(attached);
			}
		}
	}
}
